<template>
	<view class="warrper">
		<view class="fixed">
			<!-- 状态栏 -->
			<view class="statusBar" :style="'height:'+statusBarHeight+'px'"></view>
			<view class="myheader padding-sm font-sub-title">
				首页
			</view>
		</view>
		<view v-if="role=='user'" class="top-container flex padding-sm" style="border-bottom: 8px solid #F1f1f1;" :style="{marginTop:navHeight}">
			
			<view class="margin-left-sm margin-right">
				<jy-image placeholder='/static/loading.gif' :src="getAvatar(userInfo.AVATAR)" class="cu-avatar my-avatar " style="border-radius: 5px;"></jy-image>
			</view>
			<view class="flex-treble" @click="goUserInfo">
				<view class="img-group margin-bottom-sm font-normal flex justify-between">
					<view class="font-normal flex">
						<view style="height:60rpx;" :style="userInfo.NAME.length>5?'width: 200rpx;':''" class="margin-right-sm font-normal uni-ellipsis">{{ userInfo.NAME||'暂无数据' }}</view>
					</view>
					<view class="font-normal">
						<text class="margin-right-sm">{{ userInfo.PROVINCE||'暂无数据' }}</text>
						<text class="margin-right-sm">{{ userInfo.CITY||'暂无数据'}}</text>
						<text class="margin-right-sm">{{ userInfo.DISTRICT||'暂无数据' }}</text>
					</view>
				</view>
				<view class="flex justify-between align-center font-normal">
					<text v-if="state==1" class="text-blue">{{bindName}}</text>
					<text class="margin-right-sm text-red" v-if="state==0" >未连接</text>
					<text class="margin-right-sm text-green" v-if="state==1" >已连接</text>
					<text class="margin-right-sm text-blue" v-if="state==2" >连接中...</text>
					<view class="flex justify-end align-center">
						<battery :power="battery" v-if="state==1&&battery!=''"></battery>
						<text class="font-small text-gray margin-right-sm margin-left-sm" v-if="state==1&battery!=''">{{battery}}%</text>
					</view>
				</view>
			</view>
		</view>
		<view v-if="role=='medicalstaff'" class="top-container flex padding-sm" style="border-bottom: 8px solid #F1f1f1;"
		 :style="{marginTop:navHeight}">
			<view class="margin-left-sm margin-right">
				<jy-image placeholder='/static/loading.gif'  style="border-radius: 5px;"  class="cu-avatar my-avatar " :src="getAvatar(userInfo.AVATAR)"></jy-image>
			</view>
			<view class="flex-treble">
				<view class="img-group margin-bottom-sm font-normal flex justify-between">
					<view class="font-normal">
						<text class="margin-right-sm">{{ userInfo.NAME }}</text>
						<text class="margin-right-sm">{{ userInfo.POSITION }}</text>
					</view>
					<text class="margin-right-sm font-small">{{ nowDate }}</text>
				</view>
				<view class="flex justify-between font-normal">
					<view class="font-normal">
						<text class="margin-right-sm">{{ userInfo.MAJOR }}</text>
						<text class="margin-right-sm">{{ userInfo.CITY}}</text>
						<text class="margin-right-sm">{{ userInfo.DISTRICT }}</text>
					</view>
					<text class="margin-right-sm ">{{userInfo.hospitalName}}</text>
				</view>
			</view>
		</view>
		
		
		<carousel :img-list="swiperList"  @selected="selectedBanner"/>

		<view v-if="role=='user'">

			<view class="cu-list menu sm-border">
				<view class="cu-item border_bottom flex-direction bg-white" @tap="handleToDetail('/pages/health/temperature')">
				
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/temprature.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">体温</view>
						</view>
						<view class="font-small margin-right">{{ temperature.terminalTime?temperature.terminalTime.substring(0,16):'' }}</view>
					</view>
				
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="margin-left font-normal" v-if="temperature.temperature">{{ temperature.temperature }}℃</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<view v-if="temperature.temperature" :class="['font-normal margin-left', getTemperatureStandard(temperature.temperature) == '正常' ? 'text-green': 'text-red']">{{ getTemperatureStandard(temperature.temperature)}}</view>
					</view>
				</view>
				<view class="cu-item border_bottom bg-white flex-direction" @tap="handleToDetail('/pages/health/heart')">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/heart.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">心率</view>
						</view>
						<view class="font-small margin-right">{{ heart.terminalTime?heart.terminalTime.substring(0,16):'' }}</view>
					</view>
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="font-normal margin-left" v-if="heart.heartRate">{{ heart.heartRate }}次/分</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<view v-if="heart.heartRate" :class="['font-normal margin-left', getHeartStand(heart.heartRate) == '正常' ? 'text-green': 'text-red']">{{ getHeartStand(heart.heartRate) }}</view>
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" @tap="handleToDetail('/pages/health/blood')">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/blood.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">血压</view>
						</view>
						<view class="font-small margin-right">{{ blood.terminalTime?blood.terminalTime.substring(0,16):'' }}</view>
					</view>
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="font-normal margin-left" v-if="blood.sbp">{{ blood.sbp }}/{{ blood.dbp }}mmHg</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<view  v-if="blood.sbp" :class="['font-normal margin-left', getStand(blood.sbp,blood.dbp) == '正常' ? 'text-green': 'text-red']">{{ getStand(blood.sbp,blood.dbp) }}</view>
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" @tap="handleToDetail('/pages/health/bloodoxygen')">
				
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/oo.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">血氧</view>
						</view>
						<view class="font-small margin-right">{{ bloodOxygen.terminalTime?bloodOxygen.terminalTime.substring(0,16):'' }}</view>
					</view>
				
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="margin-left font-normal" v-if="bloodOxygen.OOValue">{{ bloodOxygen.OOValue }}%</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<view v-if="bloodOxygen.OOValue" :class="['font-normal margin-left', getBloodOxygenStand(bloodOxygen.OOValue) == '正常' ? 'text-green': 'text-red']">{{ getBloodOxygenStand(bloodOxygen.OOValue)}}</view>
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" @tap="handleToDetail('/pages/health/respiratory')">
				
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/respiratoryRate.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">呼吸率</view>
						</view>
						<view class="font-small margin-right">{{ respiratoryRate.terminalTime?respiratoryRate.terminalTime.substring(0,16):'' }}</view>
					</view>
				
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="margin-left font-normal" v-if="respiratoryRate.respiratoryRateValue">{{ respiratoryRate.respiratoryRateValue }}次/分</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<view v-if="temperature.temperature" :class="['font-normal margin-left', getRepiratoryStandard(temperature.respiratoryRateValue) == '正常' ? 'text-green': 'text-red']">{{ getTemperatureStandard(temperature.temperature)}}</view>
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" style="height: 225rpx;" @tap="handleToDetail('/pages/health/sleep')">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/sleep.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">睡眠</view>
						</view>
						<view class="font-small margin-right">{{ getFormatTime(sleep.startTime)?getFormatTime(sleep.startTime).substring(0,16):''}}</view>
					</view>
					<view class="cu-item-bottom">
						<view class="font-normal" style="margin-left: 30rpx;">深度睡眠：{{ getTime(sleep.deepSleepTotal) }}, 浅度睡眠：{{ getTime(sleep.lightSleepTotal) }}</view>
						<view :class="['font-normal margin-left', getSleepStandard(Number(sleep.deepSleepTotal)+Number(sleep.lightSleepTotal))== '睡眠较差' ? 'text-red': 'text-green']">{{ getSleepStandard(Number(sleep.deepSleepTotal)+Number(sleep.lightSleepTotal)) }}</view>
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" @tap="handleToDetail('/pages/health/exercise')">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/exercise.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">运动</view>
						</view>
						<view class="font-small margin-right">{{ step.terminalTime?step.terminalTime.substring(0,16):'' }}</view>
					</view>

					<view class="flex justify-start cu-item-bottom align-center">
						<view class="margin-left font-normal" v-if="step.stepNumber">{{ step.stepNumber }}步</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<view v-if="step.stepNumber" :class="['font-normal margin-left', getStepStand(step.stepNumber) == '适中' ? 'text-green': 'text-red']">{{ getStepStand(step.stepNumber) }}</view>
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" style="height: auto;" @tap="handleToDetail('/pages/health/position')">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/position.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">位置</view>
						</view>
						<view class="font-small margin-right">{{ location.terminalTime?location.terminalTime.substring(0,16):'' }}</view>
					</view>
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="margin-left font-normal" v-if="location.address" style="width: 720rpx;">{{ location.address}}</view>
						<view class="font-normal margin-left" v-else>暂无数据</view>
						<!-- 						<view  v-if="position.isDeviate" :class="['font-normal margin-left', position.isDeviate==1 ? 'text-red': 'text-green']">{{ position.isDeviate==1?'已偏离':'未偏离' }}</view>
-->
					</view>
				</view>
				<view class="cu-item border_bottom flex-direction bg-white" style="height: auto;" @tap="handleToDetail('/pages/health/report/index')">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<image src="/static/img/report.png" class="uni-icon-img icon-item margin-left">
							</image>
							<view class="titletext font-normal margin-left-sm">健康报告</view>
						</view>
						<view class="font-small margin-right">{{nowDate.substring(0,16)}}</view>
					</view>
					<view class="flex justify-start cu-item-bottom align-center">
						<view class="margin-left font-normal" style="width: 720rpx;">查看我的健康报告</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else>
			<view class="cu-list menu sm-border" v-if="varList.length!=0">

				<view class="cu-item border_bottom flex-direction bg-white" v-for="data in varList" @tap="handleToDetail('/pages/health/report/index?data='+JSON.stringify(data))">
					<view class="flex justify-between align-center cu-item-top">
						<view class="flex align-center">
							<jy-image mode="aspectFill" placeholder='/static/loading.gif' class="uni-icon-img icon-item margin-left" :src="getAvatar(data.avatar)"></jy-image>
							<view class="flex">
								<view class="titletext font-normal margin-left-sm uni-ellipsis" style="width: 110rpx;">{{data.name}}</view>
								<view class="titletext font-normal"> {{getAge(data.idcard)}}岁 {{data.city}}{{data.district}}</view>
							</view>
						</view>
						<view class="font-small margin-right">{{ data.healthData?data.healthData.terminalTime:'' }}</view>
					</view>
					<view class="flex justify-start cu-item-bottom align-center ">
						<view class="font-small margin-left" v-if="data.healthData">
							<p class="uni-ellipsis">心率：{{data.healthData.heartValue}}次/分；血压：{{data.healthData.sbpvalue}}/{{data.healthData.dbpvalue}}mmHg；</p>
						</view>
						<view class="font-small margin-left" v-else>
							<p class="uni-ellipsis">暂无数据</p>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="no_data">
				<image src="../../static/img/no_data.png" class="no_data_img" mode="widthFix"></image>
				<view class="font-sub-title">暂无数据</view>
			</view>
		</view>
	</view>
</template>

<script>
	import _config from '../../config/index.js'; // 导入私有配置
	import carousel from '@/components/vear-carousel/vear-carousel'
	import {
		formatDate,
		formatHour
	} from '@/utils/datetime.js'
	import {
		sleepStandard,
		temperatureStandard,
		bloodStandard,
		stepStandard,
		heartStandard,
		bloodoxygenStandard,
		repiratoryStandard
	} from '@/utils/standard.js'
	import battery from "@/components/battery/battery.vue"
	import constant from '../../config/constant.js'
	import time from '@/common/free-lib/time.js'
	import {
		mapGetters
	} from 'vuex'
	import Vue from 'vue'
	var that;
	const TTSSpeaker = uni.requireNativePlugin('Karma617-TTSSpeaker');
	const bandSDK = uni.requireNativePlugin('BandSDK')
	const hgService = uni.requireNativePlugin("HG-Background");
	
	export default {
		components: {
			battery,
			carousel
		},
		computed: {
			...mapGetters(['navHeight']),
		},
		data() {
			return {
				statusBarHeight: Vue.prototype.StatusBar,
				role: uni.getStorageSync("role"),
				battery: '',
				nowDate: '',
				blood: uni.getStorageSync("blood")||'',
				heart: uni.getStorageSync("heart")||'',
				step: uni.getStorageSync("step")||'',
				respiratoryRate:uni.getStorageSync("respiratoryRate")||'',
				bloodOxygen:uni.getStorageSync("bloodOxygen")||'',
				location: uni.getStorageSync("location")||'',
				temperature:uni.getStorageSync("temperature")||'' ,
				sleep: uni.getStorageSync("sleep")||'',
				userInfo: {},
				user: '',
				varList: [],
				avatar: _config.NGINX_SERVER + 'imgs/avatar/avatar.jpg',

				//语音播报
				speed: 2.5, //语速
				pitch: 2, //语调

				//轮播图
				cardCur: 0,
				swiperList: [],

				state: 0 ,//设备连接情况
				count:0,
				
				bindName:uni.getStorageSync("bindName")||""
			}
		},
		onReady() {
			that = this;
			TTSSpeaker.init(function(result) {

			});
			hgService.config({
			    "title":"红樱桃健康",
			    "content":"红樱桃健康正在后台运行中",
			    "taskTime":1000*60*10,//任务执行频率,
			    "autoStartService":true,//是否根据监听到的广播自启动服务
			    "autoWakeUp":false //是否自动定时点亮屏 30s
			});
			if(!uni.getStorageSync("autoOpen")){
				uni.showModal({
					title:"自启动开启提醒",
					content: '为了实时监测您的健康状况，建议您将应用自启动开启',
					showCancel: false,
					confrimText: '去设置',
					success: (res) => {
						if (res.confirm) {
							uni.setStorageSync("autoOpen",true)
							 hgService.showSafeSetting();
						}
					},
				})
			}
		},
		onLoad() {
			that = this;
			var loginInfo = uni.getStorageSync("autoInfo")
			var params = {
				phone: '',
				password: '',
				loginType: "1"
			}
			if(!loginInfo){
				uni.reLaunch({
					url: '/pages/login/login',
				})
				return;
			}
			var result=hgService.checkIfLimited();
			if(result.isLimit){
				hgService.requestIgnoreLimit();
			}
			hgService.startService();
			
			
			that.$http.getBanner().then(function(res){
				that.swiperList = res.result
			})

			setInterval(function(){
				that.syncLocation();
				bandSDK.connectState(res => {
					if (res == "disconnected") {
						bandSDK.initClient(res=>{
						})
						var main = plus.android.runtimeMainActivity();
						var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
						var BAdapter = new BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter.isEnabled()) {
							BAdapter.enable(); //启动蓝牙
						}
						that.state = 0
						
						that.autoConnect(function(){
							that.state = 1
							that.getnewMesg()
							that.pushWeather()
						})
					} else if(res=="connected"){
						that.count++;
						that.state = 1
						that.syncAll();
						that.syncHeart();
						that.syncSleep();
						that.syncSport();
					}
				})
			},1000*61*10)
			var globalEvent = uni.requireNativePlugin('globalEvent');
			globalEvent.addEventListener('doJob', function() {
				that.syncLocation();
				bandSDK.connectState(res => {
					if (res == "disconnected") {
						bandSDK.initClient(res=>{
						})
						var main = plus.android.runtimeMainActivity();
						var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
						var BAdapter = new BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter.isEnabled()) {
							BAdapter.enable(); //启动蓝牙
						}
						that.state = 0
						
						that.autoConnect(function(){
							that.state = 1
							that.getnewMesg()
							that.pushWeather()
						})
					} else if(res=="connected"){
						if(uni.getStorageSync("userDisconnect")){
							that.state=0
							return;
						}
						that.count++;
						that.state = 1
						that.syncAll();
						that.syncHeart();
						that.syncSleep();
						that.syncSport();
					}
				})
			});
			uni.$on('refresh',function(){
				that.state=1
				that.getnewMesg()
				that.pushWeather()
			})
			setTimeout(function() {
				TTSSpeaker.speak("         欢迎使用红樱桃健康", 2);
			}, 500)
			if (loginInfo != null&&loginInfo!=''&&loginInfo!=undefined) {
				
				if (uni.getStorageInfoSync("isToggle")||false) {
					return;
				}
				params.phone = loginInfo.phone;
				params.password = loginInfo.password;
				that.$store.dispatch('login', params).then(res => {
					if (res.code === 1) {
						uni.setStorageSync("token", res.result.token)
					} else {
						var first = uni.getStorageSync("first") || false
						if (!first) {
							return;
						}
						uni.showToast({
							icon: 'none',
							position: 'center',
							title: "登录信息失效，请重新登录"
						});
						uni.reLaunch({
							url: '/pages/login/login',
						})
					}
				}).catch(() => {
					uni.showToast({
						icon: 'none',
						position: 'center',
						title: "登录信息失效，请重新登录"
					});
					uni.reLaunch({
						url: '/pages/login/login',
					})
				})
			}
		},
		onUnload() {
			uni.$off('refresh',function(){
				this.getnewMesg()
				this.pushWeather()
			})
		},
		onShow(e) {		
			this.userInfo = uni.getStorageSync("userInfo")
			this.bindName =  uni.getStorageSync("bindName")||""
			this.user = uni.getStorageSync("userInfo")
			if (this.userInfo == undefined || this.userInfo == null || this.userInfo == '') {
				// 如果本地没有账号信息，就提示用户必须登录
				uni.reLaunch({
					url: '/pages/login/login'
				})
				return;
			} else {
				if (that.user.NAME == null || that.user.NAME == "" || that.user.NAME == undefined) {
					that.userInfo.NAME = ""
					
					uni.showModal({
						title: '温馨提示',
						content: '请您先完善个人信息',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: "/pages/user/info"
								})
							}
						}
					});
				}
				if (this.role == 'user') {
					this.syncLocation()
				} else {
					this.getSignUserList()
				}
			}
			if (this.role == 'user') {
				bandSDK.connectState(res => {
					if (res == "disconnected") {
						bandSDK.initClient(res=>{
						})
						var main = plus.android.runtimeMainActivity();
						var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
						var BAdapter = new BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter.isEnabled()) {
							BAdapter.enable(); //启动蓝牙
						}
						that.state = 0
						that.autoConnect(function(){
							uni.startPullDownRefresh()
						})
					} else if(res=="connected"){
						that.state = 1
						that.nowDate = formatDate(new Date());
						that.getnewMesg(true)
					}
				})
				this.$http.getFollowApplyList().then((res) => {
					if (res.code == 1) {
						var followNum = res.result.length
						uni.setStorageSync("followNum", followNum);
						if (followNum != 0) {
							uni.showTabBarRedDot({
								index: 3
							})
						}
					}
				})
			} else {
				this.$http.getApplySignList().then((res) => {
					if (res.code == 1) {
						var signNum = res.result.length
						if (signNum != 0) {
							uni.showTabBarRedDot({
								index: 3
							})
						}
						uni.setStorageSync("signNum", signNum);
					}
				})
			}
		},
		onPullDownRefresh() {
			that.swiperList=[]
			that.$http.getBanner().then(res => {
				that.swiperList = res.result
			})
			if (this.role == 'user') {
				this.syncLocation()
				bandSDK.connectState(res => {
					if (res == "disconnected") {
						bandSDK.initClient(res=>{
						})
						that.state = 0
						var main = plus.android.runtimeMainActivity();
						var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
						var BAdapter = new BluetoothAdapter.getDefaultAdapter();
						if (!BAdapter.isEnabled()) {
							BAdapter.enable(); //启动蓝牙
							setTimeout(function(){
								that.autoConnect(function(){
									that.state = 1
									that.getnewMesg()
									that.pushWeather()
								})
								uni.stopPullDownRefresh()
							},1000)
						}else{
							var isFirstConnect = uni.getStorageSync("isFirstConnect")||false
							if(!isFirstConnect){
								uni.showToast({
									"title":"请绑定手环",
									"icon":"none",
									"position":"bottom"
								})
								uni.stopPullDownRefresh();
								return;
							}
							uni.stopPullDownRefresh()
							that.autoConnect(function(){
								that.state = 1
								that.getnewMesg()
								that.pushWeather()
							})
						}
					} else if(res=="connected"||res==6) {
						if(uni.getStorageSync("userDisconnect")){
							uni.stopPullDownRefresh()
							that.state=0
							uni.showToast({
								"title":"请绑定手环",
								"icon":"none",
								"position":"bottom"
							})
							return;
						}
						that.state = 1
						that.getnewMesg()
						that.pushWeather()
					}
				})
			} else {
				this.getSignUserList()
			}
		},
		methods: {
			selectedBanner(item, index) {
				
			},
			getAvatar(avatar){
				return avatar?avatar:_config.NGINX_SERVER + 'imgs/avatar/avatar.jpg'
			},
			test(){
				uni.showToast({
					title:'次数:'+that.count,
					position:'bottom',
					icon:'none'
				})
			},
			autoConnect(callback){
				var isFirstConnect = uni.getStorageSync("isFirstConnect")||false
				if(!isFirstConnect){
					return;
				}
				this.state=2;
				setTimeout(function(){
					if(that.state==2){
						uni.showToast({
							"title":"请确保手环设备在手机附近",
							position:"bottom",
							icon:"none"
						})
						that.state=0
					}
				},10000)
				var mac = uni.getStorageSync("bindMac")
				bandSDK.connectBle({
					'mac':mac
				},res=>{
					if(res=='success'){
						uni.setStorageSync("isFirstConnect",true)
						uni.removeStorageSync("userDisconnect")
						callback()
					}
				})
			},
			pushWeather() {
				var lowTemp, highTemp, curTemp, type,windDirection,windPower,currentGeographicLocation,lunarPhaseInfo
				var locationInfo = uni.getStorageSync("location")
				var location = locationInfo.longitude+','+locationInfo.latitude
				uni.request({
					url: `https://devapi.heweather.net/v7/weather/now?location=${location}&key=d22da7ece3bb4662b57523de84aa791f`,
					success(res) {
						if (res.data.code == 200) {
							curTemp = res.data.now.temp
							windDirection = res.data.now.windDir
							windPower = res.data.now.windScale
							currentGeographicLocation = uni.getStorageSync("location").address
							if (res.data.now.text.indexOf("晴") != -1) {
								type = 1
							} else if (res.data.now.text.indexOf("云") != -1||res.data.now.text.indexOf("阴") != -1) {
								type = 2
							} else if (res.data.now.text.indexOf("雨") != -1) {
								type = 4
							} else if (res.data.now.text.indexOf("雪") != -1) {
								type = 5
							} else if (res.data.now.text.indexOf("雾") != -1) {
								type = 6
							} else {
								type = 0
							}
							uni.request({
								url: `https://devapi.heweather.net/v7/weather/3d?location=${location}&key=d22da7ece3bb4662b57523de84aa791f`,
								success(res) {
									if (res.data.code == 200) {
										lowTemp = res.data.daily[0].tempMin
										highTemp = res.data.daily[0].tempMax
										lunarPhaseInfo = res.data.daily[0].moonPhase
										bandSDK.appTodayWeather({
											lowTemp: lowTemp,
											highTemp: highTemp,
											curTemp: curTemp,
											type: type
											// windDirection:windDirection,
											// windPower:windPower,
											// currentGeographicLocation:currentGeographicLocation,
											// lunarPhaseInfo:lunarPhaseInfo
										}, res => {
	
										})
									}
								}
							})
						}
					}
				})
			},
			getDeviceInfo() {
				bandSDK.getDeviceInfo(res => {
					that.battery = res.data.deviceBatteryValue;
				})
				setTimeout(function(){
					if(that.battery==""){
						that.getDeviceInfo()
					}
				},1000)
			},
			goUserInfo(){
				var main = plus.android.runtimeMainActivity();
				var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
				var BAdapter = new BluetoothAdapter.getDefaultAdapter();
				if (!BAdapter.isEnabled()) {
					BAdapter.enable(); //启动蓝牙
					uni.navigateTo({
						"url": "/pages/bluetooth/bluetooth"
					})
				}else{
					uni.navigateTo({
						"url": "/pages/bluetooth/bluetooth"
					})
				}
			},
			getStand(sbp, dbp) {
				return bloodStandard(sbp, dbp)
			},
			getStepStand(step) {
				return stepStandard(step)
			},
			// cardSwiper
			cardSwiper(e) {
				this.cardCur = e.detail.current
			},
			getFormatTime(time){
				return formatDate(time);
			},
			getAge(idcard) {
				if (idcard != '') {
					var identityCard = idcard
					var len = identityCard.length;
					if (len == 0) {
						return 0;
					} else {
						if ((len != 15) && (len != 18)) //身份证号码只能为15位或18位其它不合法
						{
							return 0;
						}
					}
					var strBirthday = "";
					if (len == 18) //处理18位的身份证号码从号码中得到生日和性别代码
					{
						strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
					}
					if (len == 15) {
						strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10,
							2);
					}
					//时间字符串里，必须是“/”
					var birthDate = new Date(strBirthday);
					var nowDateTime = new Date();
					var age = nowDateTime.getFullYear() - birthDate.getFullYear();
					//再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
					if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() &&
							nowDateTime.getDate() < birthDate.getDate())) {
						age--;
					}
					return age;
				}
				return 0
			},
			getSignUserList() {
				this.nowDate = formatDate(new Date());
				this.$http.getSignUserList().then((res) => {
					if (res.code === 1) {
						that.varList = res.result;
						uni.showToast({
							"title": "刷新成功",
							"position": "bottom",
							"icon": "none"
						})
					} else {
						uni.showToast({
							"title": res.message,
							"position": "bottom",
							"icon": "none"
						})
					}
					uni.stopPullDownRefresh()
				})
			},
			getnewMesg(flag = false) {
				this.nowDate = formatDate(new Date());
				if (this.state == 1) {
					that.getDeviceInfo()
					if(!flag){
						uni.showLoading({
							"title": "同步中..."
						})
					}
					that.syncAll();
					that.syncHeart();
					that.syncSleep();
					that.syncSport()
					setTimeout(function() {
						uni.hideLoading()
						uni.stopPullDownRefresh()
					}, 2000)
				} else {
					uni.showToast({
						"title": "请连接手环",
						"position": "bottom",
						"icon": "none"
					})
					uni.stopPullDownRefresh()
					return;
				}
			},
			syncLocation() {
				plus.geolocation.getCurrentPosition(function(res){
					var data = {
						latitude:res.coords.latitude,
						longitude:res.coords.longitude,
						address:'',
						desc:''
					}
					if(res.addresses==null||res.addresses==''||res.addresses==undefined){
						uni.request({
							url:`http://api.cellocation.com:81/regeo/?lat=${res.coords.latitude}&lon=${res.coords.longitude}&coord=gcj02&output=json`,
							success(result) {
								data.address = result.data.address
							}
						})
					}else{
						data.address = res.addresses
					}
					data.terminalTime = formatDate(new Date())
					that.location = data;
					var oldLocation = uni.getStorageSync("location")
					data.startTime = new Date().getTime()
					data.userId = that.userInfo.PATIENT_ID
					if((data.startTime-oldLocation.startTime)<1000*60*28){
						return;
					}
					uni.setStorageSync("location",that.location)
					uni.request({
						url:_config.SYNCDATA_BASE+"data-receive/uploadLocation",
						data:data,
						method:"POST",
						header:{
							authentication:"2833df6a-9384-483d-a0d6-25fd5f891cae"
						},
						success(res) {
							if(res.data=="receive successfully"){
							}
						}
					})
					
				},function(err){
					if(err.code==1){
						uni.showToast({
							"title":"请打开GPS定位或检查应用定位权限",
							"position":"bottom",
							"icon":"none"
						})
					}else if(err.code==2){
						uni.showToast({
							"title":'定位失败，由于设备当前 GPS 状态差（或网络不畅）,建议持设备到相对开阔的露天场所再次尝试',
							"position":"bottom",
							"icon":"none"
						})
					}
					
				})
			},
			syncHeart() {
				bandSDK.healthHistoryData({
					type: constant.Health_HistoryHeart
				}, data => {
					
					if(data==null){
						return;
					}
					var len = data.length
					var last = data[len - 1]
					that.heart = {
						heartRate: last.heartValue,
						terminalTime: formatDate(last.heartStartTime)
					}
					if(that.heart.terminalTime==uni.getStorageSync("heart").terminalTime){
						return;
					}
					uni.setStorageSync("heart",that.heart)
					var PATIENT_ID= that.userInfo.PATIENT_ID
					var newData = []
					for(var i=0;i<len;i++){
						if(data[i].heartValue==0){
							continue
						}
						data[i].userId = PATIENT_ID
						newData.push(data[i])
					}
					
					uni.request({
						url:_config.SYNCDATA_BASE+"data-receive/uploadHeart",
						data:newData,
						method:"POST",
						header:{
							authentication:"2833df6a-9384-483d-a0d6-25fd5f891cae"
						},
						success(res) {
							if(res.data=="receive successfully"){
								setTimeout(function() {
									var dif = time.getDisMinute(that.blood.terminalTime.substring(0,16));
									if (that.blood != '' && that.heart != ''&&dif<15) {
										TTSSpeaker.speak("      您的血压为" + that.blood.sbp + '/' + that.blood.dbp + "毫米汞柱，心率为" + that.heart.heartRate + "次/分",1);
									}
								}, 2000)
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteHeart,
								},res=>{
								})
							}
						}
					})
					
				});
			},
			syncSleep() {
				bandSDK.healthHistoryData({
					type: constant.Health_HistorySleep
				}, data => {
					if(data==null){
						return;
					}
					var last = data[data.length - 1]
					that.sleep = last
					uni.setStorageSync("sleep",that.sleep)
					var PATIENT_ID= that.userInfo.PATIENT_ID
					for(var i=0;i<data.length;i++){
						data[i].userId = PATIENT_ID
					}
					
					var arr=[]
					if(!Array.isArray(arr)){
						arr.push(data)
					}else{
						arr=data
					}
					uni.request({
						url:_config.SYNCDATA_BASE+"data-receive/uploadSleep",
						data:arr,
						method:"POST",
						header:{
							authentication:"2833df6a-9384-483d-a0d6-25fd5f891cae"
						},
						success(res) {
							if(res.data=="receive successfully"){
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteSleep,
								},res=>{
								})
							}
						}
					})
					
				});
			},
			syncSport(){
				bandSDK.healthHistoryData({
					type: constant.Health_HistorySport
				}, data => {
					if(data==null){
						return;
					}
					var PATIENT_ID= that.userInfo.PATIENT_ID
					var len=data.length
					for(var i=0;i<len;i++){
						data[i].userId = PATIENT_ID
					}
					uni.request({
						url:_config.SYNCDATA_BASE+"data-receive/uploadStep",
						data:data,
						method:"POST",
						header:{
							authentication:"2833df6a-9384-483d-a0d6-25fd5f891cae"
						},
						success(res) {
							if(res.data=="receive successfully"){
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteSport,
								},res=>{
								})
							}
						}
					})
					
				});
			},
			syncAll() {
				bandSDK.healthHistoryData({
					type: constant.Health_HistoryAll
				}, data => {
					if(data==null){
						return;
					}
					var len = data.length
					var last = data[len - 1]
					if(last.DBPValue!=0){
						that.blood = {
							sbp: last.DBPValue,
							dbp: last.SBPValue,
							terminalTime: formatDate(last.startTime)
						}
						if(that.blood.terminalTime==uni.getStorageSync("blood").terminalTime){
							return;
						}
						uni.setStorageSync("blood",that.blood)
					}
					if(last.tempIntValue!=0){
						that.temperature = {
							temperature: last.tempIntValue + "." + last.tempFloatValue,
							terminalTime: formatDate(last.startTime)
						}
						uni.setStorageSync("temperature",that.temperature)
					}

					that.step = {
						stepNumber: last.stepValue,
						terminalTime: formatDate(last.startTime)
					}
					uni.setStorageSync("step",that.step)
					
					if(last.OOValue!=0){
						that.bloodOxygen = {
							OOValue: last.OOValue,
							terminalTime: formatDate(last.startTime)
						}
						uni.setStorageSync("bloodOxygen",that.bloodOxygen)
					}
					if(last.respiratoryRateValue!=0){
						that.respiratoryRate = {
							respiratoryRateValue: last.respiratoryRateValue,
							terminalTime: formatDate(last.startTime)
						}
						uni.setStorageSync("respiratoryRate",that.respiratoryRate)
					}
					
					var PATIENT_ID= that.userInfo.PATIENT_ID
					var newData = []
					for(var i=0;i<len;i++){
						if(data[i].DBPValue==0||data[i].respiratoryRateValue==0||data[i].tempIntValue<30||data[i].OOValue==0){
							continue;
						}
						data[i].userId = PATIENT_ID
						newData.push(data[i])
					}
					if(newData.length==0){
						return;
					}
					//上传服务器
					uni.request({
						url:_config.SYNCDATA_BASE+"data-receive/uploadAll",
						data:newData,
						method:"POST",
						header:{
							authentication:"2833df6a-9384-483d-a0d6-25fd5f891cae"
						},
						success(res) {
							if(res.data=="receive successfully"){
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteAll,
								},res=>{
								})
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteBlood,
								},res=>{
								})
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteBloodOxygen,
								},res=>{
								})
								bandSDK.deleteHealthHistoryData({
									type:constant.Health_DeleteTemp,
								},res=>{
								})
							}
						}
					})
				});
			},
			handleToDetail(path) {
				uni.navigateTo({
					url: path
				})
			},
			getSleepStandard(time) {
				return sleepStandard(time);
			},
			getTemperatureStandard(temp) {
				return temperatureStandard(temp)
			},
			getHeartStand(heart) {
				return heartStandard(heart)
			},
			getBloodOxygenStand(bloodoxygen){
				return bloodoxygenStandard(bloodoxygen)
			},
			getRepiratoryStandard(value){
				return repiratoryStandard(value)
			},
			getNow() {
				return formatDate(new Date());
			},
			getTime(time) {
				return formatHour(time);
			}
		}
	}
</script>

<style scoped>
	page {
		background-color: #F1F1F1;
	}

	.warrper {
		overflow: hidden;
	}

	.margin-left {
		margin-bottom: 20rpx;
	}

	.warrper .content {
		padding-top: 45rpx;
		padding-bottom: 45rpx;
	}

	.top-container {
		background-color: #fff;
		height: 150rpx;
	}

	.img-group {
		height: 30%;
	}

	.img-right {
		height: 100%;
		width: 100%;
	}

	.titletext {
		margin-top: -3px;
	}

	.main-container {
		background-color: #f5f5f5;
		height: 80vh;
		overflow-y: scroll;
	}

	.item-content {
		text-align: center;
	}

	.item-content-center {
		width: 30vw;
		text-align: left;
		margin-left: 6vw;
	}

	.item-content-center .mytext {
		width: 34vw;
	}

	.mytext uni-text {
		width: 100%;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.uni-icon-img {
		width: 64rpx;
		height: 64rpx;
	}

	.time {
		font-size: 0.5rem;
	}

	.desc {
		height: 50%;
	}

	.icon-item {
		border-radius: 5px;
		overflow: hidden;
		width: 50rpx;
		height: 50rpx;
		margin-bottom: 5rpx;
	}

	.doctor_img {
		width: 100rpx;
		height: 100rpx;
	}

	.cu-item {
		height: 170rpx;
		padding-top: 25rpx !important;
	}

	.border_bottom {
		border-bottom: 8px solid #F1F1F1;
	}

	.cu-item-top {
		width: 740rpx;
	}

	.cu-item-bottom {
		width: 740rpx;
		margin-top: 0;
	}

	.cu-item::after {
		width: 0 !important;
	}

	.cu-item:hover {
		background: rgba(225, 225, 225, 0.3);
	}

	.no_data {
		margin-top: 150rpx;
	}

	.no_data_img {
		margin-top: 150rpx;
	}

	.my-avatar {
		width: 100rpx;
		height: 100rpx;
	}
</style>
